import { Breadcrumb } from "antd";
import { HomeOutlined } from "@ant-design/icons";
import { useLocation } from "react-router-dom";

// 修改接口定义，匹配实际的菜单数据结构
interface MenuApiData {
  id: number;
  parentId: number;
  menuName: string; // 使用 menuName 而不是 title
  url: string; // 使用 url 而不是 path
  description?: string;
  editAble: number;
  menuList?: MenuApiData[]; // 子菜单使用 menuList
  component?: string;
}

const PageBreadcrumb = () => {
  const location = useLocation();

  // 获取菜单数据
  const getMenuData = (): MenuApiData[] => {
    const userInfo = localStorage.getItem("userInfo");
    if (!userInfo) return [];

    try {
      const { role } = JSON.parse(userInfo);
      return role?.menuList || [];
    } catch (error) {
      console.error("解析用户信息失败:", error);
      return [];
    }
  };

  // 递归查找路径对应的菜单项
  const findMenuPath = (
    menus: MenuApiData[],
    targetPath: string
  ): MenuApiData[] => {
    for (const menu of menus) {
      // 使用 url 字段匹配路径
      if (menu.url === targetPath) {
        return [menu];
      }

      // 检查子菜单 (使用 menuList 字段)
      if (menu.menuList && menu.menuList.length > 0) {
        const childPath = findMenuPath(menu.menuList, targetPath);
        if (childPath.length > 0) {
          return [menu, ...childPath];
        }
      }
    }
    return [];
  };

  // 生成面包屑项
  const generateBreadcrumbItems = () => {
    const menuData = getMenuData();
    const currentPath = location.pathname;

    // 首页面包屑
    const items = [
      {
        title: (
          <span>
            <HomeOutlined />
            <span style={{ marginLeft: 4 }}>首页</span>
          </span>
        ),
      },
    ];

    // 如果不是首页，查找当前路径的菜单层级
    if (currentPath !== "/home") {
      const menuPath = findMenuPath(menuData, currentPath);

      if (menuPath.length > 0) {
        // 添加菜单路径到面包屑，使用 menuName 字段
        menuPath.forEach((menu) => {
          items.push({
            title: <span>{menu.menuName}</span>,
          });
        });
      } else {
        // 如果找不到对应菜单，使用路径生成
        const pathSegments = currentPath.split("/").filter(Boolean);
        if (pathSegments.length > 0) {
          // 尝试根据路径段找到对应的菜单名称
          const lastSegment = pathSegments[pathSegments.length - 1];
          let displayName = lastSegment.replace(/-/g, " ");

          // 尝试在所有菜单中查找包含此路径段的菜单
          const allMenus = getAllMenusFlat(menuData);
          const foundMenu = allMenus.find(
            (menu) =>
              menu.url.includes(lastSegment) || menu.component === lastSegment
          );

          if (foundMenu) {
            displayName = foundMenu.menuName;
          }

          items.push({
            title: <span>{displayName}</span>,
          });
        }
      }
    }

    return items;
  };

  // 扁平化获取所有菜单项
  const getAllMenusFlat = (menus: MenuApiData[]): MenuApiData[] => {
    let result: MenuApiData[] = [];

    menus.forEach((menu) => {
      result.push(menu);
      if (menu.menuList && menu.menuList.length > 0) {
        result = result.concat(getAllMenusFlat(menu.menuList));
      }
    });

    return result;
  };

  return (
    <Breadcrumb
      items={generateBreadcrumbItems()}
      style={{
        margin: "16px 0",
        padding: "8px 16px",
        backgroundColor: "#fafafa",
        borderRadius: "6px",
        border: "1px solid #f0f0f0",
      }}
    />
  );
};

export default PageBreadcrumb;
